package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.utils.DateUtils;
import com.atguigu.spzx.common.utils.UUIDUtils;
import com.atguigu.spzx.manager.service.FileUploadService;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.atguigu.spzx.manager.modules.properties.MinioProperties;

/**
 * <p>
 * FileUploadServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2023/10/27
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            // 创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(),minioProperties.getSecreKey())
                            .build();

            // 创建Bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                log.info("Bucket【{}】已经存在",minioProperties.getBucketName());
            }

            //获取上传的文件名称
            String originalFilename = file.getOriginalFilename();

            //组装文件的路径和名称 20231027/edf31800884849d583c0a76175cd2cf9美女.jpg
            String dateDir = DateUtils.getYYYYMMDD();
            String uuid = UUIDUtils.getSimpleUUID();
            String filename = dateDir + "/" + uuid + originalFilename;

            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(filename)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());

            //获取文件路径
            String url = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + filename;
            return url;
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
        }
    }
}
